/**
 *  全局修建者
 */

let baser = require("./baser");

/**
 * 返回baser的内部生命函数
 * @param {[{fromroomname:String,toroomname:String,num:Int}]} roomnames 
 * -> memory:[[creep.id]]
 * @returns {Int}
 */

module.exports = function (roomnames) {
    return baser(
        /**
         * 准备函数，获取下标
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.id) {
                return 1;
            }
            if (!creep.memory.g_builder_index) {
                if (!Game.rooms[creep.memory.roomname].memory.g_builder_id) {
                    Game.rooms[creep.memory.roomname].memory.g_builder_id = [];
                }
                for (let i in roomnames) {
                    if (!Game.rooms[creep.memory.roomname].memory.g_builder_id[i]) {
                        Game.rooms[creep.memory.roomname].memory.g_builder_id[i] = [];
                    }
                    for (let o = 0; o < roomnames[i].num; o++) {
                        // 该位置没有creep
                        if (!Game.getObjectById(Game.rooms[creep.memory.roomname].memory.g_builder_id[i][o]) ||
                            Game.getObjectById(Game.rooms[creep.memory.roomname].memory.g_builder_id[i][o]) == creep) {
                            Game.rooms[creep.memory.roomname].memory.g_builder_id[i][o] = creep.id;
                            creep.memory.g_builder_index = i;
                            return 2;
                        }
                    }
                }
                return 1;
            }
            return 2;
        },
        /**
         * 工作函数，获取能量
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.memory.g_builder_index) return 1;
            let fromroomname = roomnames[creep.memory.g_builder_index].fromroomname;
            if (creep.room.name != fromroomname) {
                creep.actionToRoom(fromroomname);
                return 2;
            }
            // 满了开始修建
            if (creep.store.getFreeCapacity() < 5) {
                return 3;
            }
            // 继续获取能量
            if (creep.actionWithdraw() == 1) {
                creep.actionHarvest();
            }
            return 2;
        },
        /**
         * 工作函数，修建
         * @param {Creep} creep
         */
        function (creep) {
            if (!creep.memory.g_builder_index) return 1;
            let toroomname = roomnames[creep.memory.g_builder_index].toroomname;
            if (creep.room.name != toroomname) {
                creep.actionToRoom(toroomname);
                return 3;
            }
            // 空了准备能量
            if (creep.store[RESOURCE_ENERGY] < 5) {
                return 2;
            }
            // 修建
            if (creep.actionBuild() == 1) {
                creep.actionUpgrade();
            }
            return 3;
        });
}